import numpy as np

# used to calculate competing destination factors
# whole study area
def cdwhole(mass, coord, tlambda):
    cdlist = []
    for i in range(len(mass)):
        temp = cdsingle(mass, coord, i, tlambda)
        cdlist.append(temp)
    return cdlist

def cdsingle(mass, coord, idx, tlambda):
    idx = int(idx)
    tcd = 0.0
    for i in range(len(mass)):
        if i <> idx:
            tdis = caldist(coord[i,0], coord[i,1], coord[idx,0], coord[idx,1])
            tcd += mass[i]/(tdis**tlambda)
    return tcd

def caldist(ox, oy, dx, dy):
    ox = float(ox)
    oy = float(oy)
    return ((ox - dx)**2 + (oy - dy)**2)**0.5

#--------------------------------------------------------------------------
#MAIN

if __name__ == "__main__":
    print '===================================================='
    filepath = 'C:/_DATA/migration_census_2000/REDCAPLUS_100Region/'
    file = filepath + 'census_migration_100regs_pop.csv'
    pop = build_data_list(file)
    pop = pop[:,0]
    
    file = filepath + 'redcaplus_100_centroid.csv'
    centroids = build_data_list(file)

    cd = cdwhole(pop, centroids, 1)
    headerstr = 'cd'
    fileLoc = filepath + 'temp.csv'
    np.savetxt(fileLoc, cd, delimiter=',', header = headerstr, fmt = '%s')